/*
    Static JS for Reports viewing/submission/approval

    Demo code: https://github.com/roraback/Vulnerability-Mapping/blob/master/js/controls.js
*/

// Global vars
S3.dataTables = {};
S3.dataTables.id = ['report'];
var shownReport = -1;
var submittedData = '';
var submittedDataPage = 0;
var submitDataJobID = 0;
var submitNextAction = '';
var submitDataItemIDs = '';

$(document).ready(function() {
    // Setup Events
    $('.headerRow').click(function() {
        var that = $(this);
        $('.rowForApproval').hide();
        $('.rowForApproval').prev().find('.closeReviewButton').hide();
        $('.rowForApproval').prev().find('.reviewButton').show();
        $('.headerRow.activeSection td.arrowCell .arrow').html('&rarr;');
        $('.headerRow.activeSection').removeClass('activeSection');
        that.addClass('activeSection');
        $('.headerRow.activeSection .arrow').html('&darr;');
        $('.activeContent').hide('slow');
        $('.activeContent').removeClass('activeContent');
        that.next().addClass('activeContent');
        that.parent().next().addClass('activeContent');
        $('.activeContent').fadeIn(200);
        resizeReports();
    });

    $('#filterSubmit, .panelSearchSubmit').click(filterReport);
    $('#l3_datas').change(indicatorsCheckCommune);
    $('#submitIndicators').click(function() {
        showSubmitData('indicators');
    });
    $('#submitReports').click(function() {
        showSubmitData('reports');
    });
    $('#uploadIndicatorsButton').click(uploadSubmitDataIndicators);
    //$('.loadingErrorView .indicatorsButton').click(reloadSubmitDataFromError);
    $('#submitDataFooter .reviewNextButton').click(reviewNext);
    $('#submitDataFooter .backButton').click(reviewBack);
    $('#submitDataFooter .cancelButton').click(cancelSubmitDataTypeSelection);
    $('#submitDataFooter .submitAllButton').click(submitAll);
    $('#submitDataFooter .submitMoreButton').click(submitMore);
    $('#uploadDemographicsButton').click(demographicsLoader);
    $('#submitOnlineButton').click(function() {
        if (!$(this).hasClass('disabled')) {
            // Load the indicator form
            displaySubmitOnline();
        }
    });
    $('#submitDataFooter .reviewSubmissionButton').click(function() {
        reviewSubmitData();
    });
    $('#submitDataFooter .submitButton').click(function() {
        if ($(this).hasClass('disabled')) {
            return;
        }
        if ($('.submitIndicatorsForm').is(':visible')) {
            submitSubmitData();
        } else {
            uploadSubmitDataReport(this);
        }
    });
    $('.submitIndicatorsForm input').change(function() {
        if ($('.submitIndicatorsForm input:radio:checked').length == 10) {
            $('#submitDataFooter .reviewSubmissionButton').removeClass('disabled');
        }
    });
    $('.dataSubmissionRegion input:radio').change(selectOptionSubmitData);
    
    $(window).resize(function() {
        if ($('#reportsSection').is(':visible')) {
            resizeReports();
        } else if ($('#submitDataSection').is(':visible')) {
            resizeSubmitData();
        }
    });

    // Initialise the report date filters
    $('#dateFromReports').datepicker({
        dateFormat: 'yy-mm-dd',
        changeYear: true,
        changeMonth: true,
        maxDate: '+0d',
        minDate: '-20y'
     });
    $('#dateToReports').datepicker({
        dateFormat: 'yy-mm-dd',
        changeYear: true,
        changeMonth: true,
        maxDate: '+0d',
        minDate: '-20y'
     });

    // Resize Submit Data and Reports
    resizeSubmitData();
    resizeReports();
});

// Open a dataTable of Reports to view/review
function showReports(pSection) {
    $('#table-container').empty();
    displayThanks('#reportsContent', i18n.loading_report_details, null);
    $('#lightbox, #reportsSection').fadeIn(300);
    var data = getFilteredReport();
    $.ajax({
        type: 'POST',
        url: S3.Ap.concat('/vulnerability/report/filter'),
        data: data
    }).done(function(data) {
        $('.approvalScreen').hide();
        displayReport(data);
        if (pSection == 'pending') {
            openReportRow('group_011');
        } else if (pSection == 'VCA') {
            openReportRow('group_012');
        } else {
            openReportRow('group_013');
        }
    }).fail(function() {
        $('.approvalScreen').hide();
        // @ToDo: Something meaningful
        alert('error');
    });
}

// Collect all the filter options to pass to the server
function getFilteredReport() {
    var data = new Object();
    //if ($('#l4_reports').val()) {
    //    data['location_id'] = $('#l4_reports').val();
    //} else if ($('#l3_reports').val()) {
    if ($('#l3_reports').val()) {
        data['location_id'] = $('#l3_reports').val();
    } else if ($('#l2_reports').val()) {
        data['location_id'] = $('#l2_reports').val();
    } else if ($('#l1_reports').val()) {
        data['location_id'] = $('#l1_reports').val();
    } else if ($('#l0_reports').val()) {
        data['location_id'] = $('#l0_reports').val();
    } else {
        data['location_id'] = -1;
    }
    data['from_date'] = $('#dateFromReports').val();
    data['to_date'] = $('#dateToReports').val();
    if ($('#indicatorsCheckbox').is(':checked')) {
        data['indicator'] = true;
    }
    if ($('#mapCheckbox').is(':checked')) {
        data['map'] = true;
    }
    if ($('#imagesCheckbox').is(':checked')) {
        data['images'] = true;
    }
    if ($('#reportsCheckbox').is(':checked')) {
        data['reports'] = true;
    }
    if ($('#demographicsCheckbox').is(':checked')) {
        data['demographics'] = true;
    }
    data['text'] = $('#reportTextSearch').val();
    if ($('#reportsToggle .active').hasClass('myReports')) {
        data['myReports'] = true;
    }
    return data;
}

function displayReport(data) {
    $('#table-container').empty();
    if (data) {
        $('#table-container').append(data);
        //var start = Date.now();
        S3.dataTables.initDataTable('#report', 0, true);
        //var end = Date.now();
        //var total = end - start;
        //console.log('fnInitDataTable took ' + total + 'ms');
        //var start = Date.now();
        formatTable(data);
        //var end = Date.now();
        //var total = end - start;
        //console.log('formatTable took ' + total + 'ms');
        openReportRow('group_011');
        $('#numberReports').html($('#reportCount').val());
    } else {
        $('#numberReports').html(i18n.no_entries_found);
    }
    resizeReports();
}

function formatTable() {
    $('#report').addClass('reportsTable')
                .addClass('headerTable');
    $('.group').addClass('headerLabel');
    $('#report tr').each(function() {
        var td = $(this).find('td:first');
        if (td.length === 0) {
            td = $(this).find('th:first');
        }
        td.addClass('date')
          .next().addClass('communeName')
          .next().addClass('type')
          .next().addClass('submittedBy')
          .next().addClass('status')
          .next().addClass('action');
    });
}

// Open one of the Groups in the dataTable
function openReportRow(className) {
    if (shownReport != -1) {
        hideReportDetails(shownReport);
    }
    var rows = $('.' + className);
    if (rows.length) {
        if (rows.html().indexOf('(0)') == -1) {
            S3.dataTables.accordionRow(0, 'level_1', className);
        } else if ($('.group_011').html().indexOf('(0)') == -1) {
            S3.dataTables.accordionRow(0, 'level_1', 'group_011');
        } else if ($('.group_012').html().indexOf('(0)') == -1) {
            S3.dataTables.accordionRow(0, 'level_1', 'group_012');
        } else {
            S3.dataTables.accordionRow(0, 'level_1', 'group_013');
        }
    }
}

// Switch between 'All Reports' & 'My Reports'
function toggleReports(filter) {
    switch(filter) {
        case 'myReports':
            $('.allReports').removeClass('active')
                            .html("<a href=\"javascript:toggleReports('allReports')\" title='All Reports'>" + i18n.all_reports.toUpperCase() + "</a>");
            $('.myReports').addClass('active')
                           .html(i18n.my_reports.toUpperCase());
            break;
        case 'allReports':
            $('.myReports').removeClass('active')
                           .html("<a href=\"javascript:toggleReports('myReports')\" title='My Reports'>" + i18n.my_reports.toUpperCase() + "</a>");
            $('.allReports').addClass('active')
                            .html(i18n.all_reports.toUpperCase());
            break;
    }
    filterReport();
}

function filterReport() {
    displayThanks('#reportsContent', i18n.loading_report_details, null);
    $('#table-container').empty();
    // 'id' is being picked up as '#report' from a global which then barfs when trying to select $('##report')
    //hideReportDetails(id);
    var data = getFilteredReport();
    $.ajax({
        type: 'POST',
        url: S3.Ap.concat('/vulnerability/report/filter'),
        data: data
    }).done(function(data) {
        $('.approvalScreen').hide();
        displayReport(data);
    }).fail(function() {
        // @ToDo: Something meaningful
        alert('error');
        $('.approvalScreen').hide();
    });
}

function resizeReports() {
    var reportsHeight = window.innerHeight - 111;
    var activeContentHeight = 0;
    $('.activeContent.contentTable .content').children('tr:visible').each(function() {
        activeContentHeight += $(this).innerHeight();
    });
    // activeContentHeight -= 8;
    if (reportsHeight < 507) {
        reportsHeight = 507;
    }
    if (activeContentHeight > reportsHeight - 180) {
        activeContentHeight = reportsHeight - 180;
    }
    $('#lightbox').css('height', $('#vulnerability').innerHeight() + 'px');
    $('#reportsContent, #reportFilters').css('height', reportsHeight + 'px');
    $('.activeContent.contentTable').css('height', activeContentHeight + 'px')
                                    .css('display', 'block');
}

function displayThanks(thisID, msg, timeout) {
    $(thisID + ' .approvalScreen .thanks').html(msg)
                                          .show();
    var approvalScreen = $(thisID + ' .approvalScreen');
    approvalScreen.fadeIn(300);
    var return2reports = $(thisID + ' .approvalScreen .return2reports');
    return2reports.hide();
    if (timeout) {
        approvalScreen.data('approvalTimeout', setTimeout(function() {
            approvalScreen.fadeOut(300);
        }, timeout));
        return2reports.show();
    }
}

function showReportDetails(id) {
    $.getJSON(
        S3.Ap.concat('/vulnerability/report/review'),
        {id: id}
    ).done(function(data) {
        displayReportDetails(id, data);
    }).fail(function() {
        // @ToDo: Something meaningful
        alert('error');
    });
}

function viewReportDetails(id){
    $.getJSON(
        S3.Ap.concat('/vulnerability/report/view'),
        {id: id}
    ).done(function(data){
        displayReportDetails(id, data);
    }).fail(function() {
        // @ToDo: Something meaningful
        alert('error');
    });
}

function hideReportDetails(id) {
    $('#show' + id).remove();
    var parent = $('#' + id).parent().parent();
    parent = $(parent);
    parent.find('.reviewButton').show();
    parent.find('.viewButton').show();
    parent.find('.closeReviewButton').hide();
}

function displayReportDetails(id, data) {
    if (shownReport != -1) {
        hideReportDetails(shownReport);
    }
    shownReport = id;
    var parent = $('#' + id).parent().parent();
    var nRow = document.createElement('tr');
    var nData = document.createElement('td');
    nData.colSpan = 6;
    nData.innerHTML = data;
    nRow.appendChild(nData);
    $(nRow).addClass('showReport')
           .attr('id', 'show' + id)
           .insertAfter(parent);
    parent = $(parent);
    parent.find('.reviewButton').hide();
    parent.find('.viewButton').hide();
    parent.find('.closeReviewButton').show();
    $('.approveButton, .declineButton').click(processReportDetails);
}

// Approve or Reject a Report
function processReportDetails() {
    var id = this.name.substr(7);
    $('#table-container').empty();
    hideReportDetails(id);
    var form = $('#form' + id);
    var report = form.serialize();
    var filter = getFilteredReport();
    filter['id'] = id;
    filter['report'] = report;
    var row = $('#' + id).parent().parent();
    if ($(this).hasClass('approveButton')) {
        displayThanks('#reportsContent', i18n.approval_request_submitted, null);
        $.ajax({
            type: 'POST',
            url: S3.Ap.concat('/vulnerability/report/approve'),
            data: filter
        }).done(function(data) {
            $('.approvalScreen').hide();
            displayThanks('#reportsContent', i18n.thankyou_for_your_approval, 5000);
            // Refresh vdata
            var location_id = this.data.split('location_id=')[1].split('&')[0];
            if (location_id != -1) {
                $.ajax({
                    'url': S3.Ap.concat('/vulnerability/vdata/' + location_id),
                    'success': function(data) {
                        // Copy the vdata elements across
                        for (var prop in n) {
                            vdata[prop] = n[prop];
                        }
                        // Clear the memory
                        n = null;
                    },
                    'error': function(request, status, error) {
                        if (error == 'UNAUTHORIZED') {
                            msg = i18n.gis_requires_login;
                        } else {
                            msg = request.responseText;
                        }
                        console.log(msg);
                    },
                    'dataType': 'script'
                });
            }
            displayReport(data);
        }).fail(function() {
            // @ToDo: Something meaningful
            alert('error');
            $('.approvalScreen').hide();
        });
    } else {
        displayThanks('#reportsContent', i18n.reject_request_submitted, null);
        $.ajax({
            type: 'POST',
            url: S3.Ap.concat('/vulnerability/report/decline'),
            data: filter
        }).done(function(data) {
            $('.approvalScreen').hide();
            displayThanks('#reportsContent', i18n.submission_has_been_declined, 5000);
            displayReport(data);
        }).fail(function() {
            // @ToDo: Something meaningful
            alert('error');
            $('.approvalScreen').hide();
        });
    }
}

// Submit Indicators via UI
function uploadSubmitDataIndicators() {
    /* Hide any error message */
    $('.loadingErrorView').fadeOut(300);
    var formData = new FormData($('#uploadIndicatorsForm')[0]);
    //formData.append('action', 'vulnerability_part1');
    // Tell S3Import this is an AJAX upload
    formData.append('approach', 'ajax');
    $.ajax({
        url: S3.Ap.concat('/vulnerability/import_vul_csv_part1/import.aadata'),
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    }).done(function(data) {
        if (data['Error']) {
            /* Display the error */
            $('#errormsg').html(data['Error']);
            $('.loadingErrorView').fadeIn(300);
        } else {
            submitDataJobID = data['upload_id'];
            submitDataItemIDs = data['items'];
            submitNextAction = 'vulnerability_part2';
            submittedData = data['data'];
            submittedDataPage = 0;
            $('.indicatorsStart').fadeOut(300);
            displaySubmitDataIndicators();
        }
    }).fail(function() {
        // @ToDo: Something meaningful
        alert('error');
    });
    /*
    $('.loadingView').fadeIn(300);
    $('.indicatorsStart').fadeOut(300);
    $('.loadingView .progressBar').progressbar({
    	value: 0,
    	change: function(event, ui){
    	    sillyProgressBarLoadScript('.loadingView .progressBar');
    	},
    	complete: function(event, ui){
        	if($('.loadingView').is(':visible')){
        	    $('.loadingView').fadeOut(300);
        	    $('#indicatorsSubmissionViews .loadingErrorView').fadeIn(300);
        	}
    	}
    });
    sillyProgressBarLoadScript('.loadingView .progressBar');
    */
}
function displaySubmitDataIndicators() {
    // Clear the file input field
    $('#submitDataUpload').html($('#submitDataUpload').html());
    if (submittedData) {
        var total_pages = submittedData.length;
        var page_data = submittedData[submittedDataPage];
        var page = submittedDataPage + 1;
        $('#submitDataContent .reviewIndicatorsView h3').html(i18n.review + " <span class='currentPage'>" + page + '</span> ' + i18n.of + " <span class='totalPages'>" + total_pages + '<span>');
        $('.reviewIndicatorsView h4 mark').html(page_data['location']);
        $('.reviewIndicatorsView h4 date').html(page_data['date']);
        $('.reviewIndicatorsView .indicatorReviewTable tbody tr').each(function() {
            var that = $(this);
            var indicator = that.find('td.indicatorLabels').html().substr(14);
            var rating = page_data['data'][indicator];
            that.find("input[value='" + rating + "']").prop('checked', true);
        });
        $('.reviewIndicatorsView.firstPage').fadeIn(300);
        $('#submitDataFilters').animate({
            'background-color': '#f7941d'
        }, 500);
        $('#submitDataFilters h3').hide(300);
        $('#submissionToggle').hide(300);
        if (page == 1) {
            $('#submitDataFooter mark, #submitDataFooter .reviewNextButton').fadeIn(300);
            $('.backButton').hide();
        }
        if (page > 1 && !$('.backButton').is(':visible')) {
            $('.backButton').fadeIn(300);
        }
        if (page == total_pages) {
            $('.reviewNextButton').hide();
            $('.submitAllButton').show();
        } else {
            $('.reviewNextButton').show();
            $('.submitAllButton').hide();
        }
    }
}
function reviewNext() {
    submittedDataPage = submittedDataPage + 1;
    var total_pages = submittedData.length;
    if (submittedDataPage >= total_pages) {
        submittedDataPage = total_pages - 1;
    }
    if ($('#indicatorsSubmissionViews').is(':visible')) {
        displaySubmitDataIndicators();
    } else {
        displayDemoData();
    }
}
function reviewBack() {
    submittedDataPage = submittedDataPage - 1;
    if (submittedDataPage < 0) {
        submittedDataPage = 0;
    }
    if ($('#indicatorsSubmissionViews').is(':visible')) {
        displaySubmitDataIndicators();
    } else {
        displayDemoData();
    }
}

function submitAll() {
    var details = {'approach' : 'ajax', // Tell S3Import this is an AJAX upload
                   'action' : submitNextAction,
                   'job' : submitDataJobID,
                   'mode' : 'Inclusive',
                   'selected' : JSON.stringify(submitDataItemIDs)
                   };
    $.ajax({
        url: S3.Ap.concat('/vulnerability/submitData/import.aadata'),
        type: 'POST',
        data: details
    }).done(function(data) {
        $('.reviewIndicatorsView').fadeOut(300);
        $('.reviewDemographicsView').hide();
        if (submitNextAction == 'vulnerability_part2') {
            displayThanks('#indicatorsSubmissionViews', i18n.upload_successful, null);
        } else {
            displayThanks('#dataAndReportsSubmissionViews', i18n.upload_successful, null);
        }
        $('#submitDataFooter div, #submitDataFooter mark').fadeOut(300);
        $('#submitDataFooter .submitMoreButton').fadeIn(300);
    }).fail(function() {
        // @ToDo: Something meaningful
        alert('error');
    });
}

function submitMore() {
    $('#indicatorsSubmissionViews .approvalScreen').hide();
    $('#dataAndReportsSubmissionViews .approvalScreen').hide();
    $('#submitDataFooter .submitMoreButton').fadeOut(300);
    $('#submitDataFilters').animate({ 'background-color': '#c6c6c6' }, 500);
    $('#submitDataFilters h3').fadeIn(300);
    $('#submissionToggle').fadeIn(300);
    $('#dataUploadTitle h4').html(i18n.select_data_type);
    $('#dataUploadTitle h3, .delete, .reviewTitling').hide();
    if ($('#indicatorsSubmissionViews').is(':visible')) {
        $('#submitDataUpload').html($('#submitDataUpload').html());
        $('#submitDataContent .indicatorsStart').fadeIn(300);
        $('#submitDataContent .indicatorsStart p').filter(':first').show();
    } else {
        $('#newSubmissionRegions, #dataSubmissionRegion .submissionContent').empty();
        $('#dataSubmissionRegion').removeClass('mapSubmission imageSubmission otherSubmission demographicsSubmission vcaSubmission loaded').removeAttr('style');
        $('#dataSubmissionRegion input').prop('disabled', false).prop('checked', false);
        //$('.dataSubmissionRegion.generic').removeAttr('style')
        $('#dataAndReportsSubmissionViews .dataUploadContainer').fadeIn(300);
        $('.fileType, .labelFile, .remove, .imgDesc, .labelHangRight, .checkHangRight').fadeIn(300);
        $('.dataSubmissionRegion input:radio').each(function() {
            $(this).parent().removeAttr('style');
        });
    }
}
function selectedLevel() {
    var l0 = $('#l0_datas').val();
    var l1 = $('#l1_datas').val();
    var l2 = $('#l2_datas').val();
    var l3 = $('#l3_datas').val();

    if (l3 && l2 && l1 && l0) {
        return 'l3';
    } else if (l2 && l1 && l0) {
        return 'l2';
    } else if (l1 && l0) {
        return 'l1';
    } else if (l0) {
        return 'l0';
    } else {
        return null;
    }
}

function indicatorsCheckCommune() {
    var level = selectedLevel();
    switch(level) {
        case null:
            $('#submitOnlineButton').addClass('disabled');
            disableOptionSubmitDataPanel('#dataSubmissionRegion');
            break;
        case 'l0':
        case 'l1':
            $('#submitOnlineButton').addClass('disabled');
            enableOptionSubmitDataPanel('#dataSubmissionRegion');
            $('#dataSubmissionRegion .mapOption input:radio').prop('disabled', true);
            $('#dataSubmissionRegion .imageOption input:radio').prop('disabled', true);
            $('#dataSubmissionRegion .mapOption, #dataSubmissionRegion .imageOption').css('color', '#999');
            $('#mapImage').addClass('disabled');
            $('#image').addClass('disabled');
            break;
        case 'l2':
            $('#submitOnlineButton').addClass('disabled');
            enableOptionSubmitDataPanel('#dataSubmissionRegion');
            break;
        default:
            $('#submitOnlineButton').removeClass('disabled');
            enableOptionSubmitDataPanel('#dataSubmissionRegion');
            break;
    }
}

function displaySubmitOnline() {
    $('#submitDataContent .submitIndicatorsForm input').prop('checked', false);
    $('#submitDataContent .submitIndicatorsForm, #submitDataFooter mark').fadeIn(300);
    $('#submitDataContent .indicatorsStart').fadeOut(300);
    $('#submitDataFooter .reviewSubmissionButton').addClass('disabled').fadeIn(300);
}

function reviewSubmitData() {
    var h = hdata[$('#l0_datas').val()];
    var lowestDD;
    //if ($('#l4_datas').val()) {
    if ($('#l3_datas').val()) {
        lowestDD = $('#l3_datas option:selected').html() + ' ' + h.l3 + '.';
    } else if ($('#l2_datas').val()) {
        lowestDD = $('#l2_datas option:selected').html() + ' ' + h.l2 + '.';
    } else if ($('#l1_datas').val()) {
        lowestDD = $('#l1_datas option:selected').html() + ' ' + h.l1 + '.';
    } else if ($('#l0_datas').val()) {
        lowestDD = $('#l0_datas option:selected').html() + ' ' + i18n.country + '.';
    }
    if ($('#submitDataContent .submitIndicatorsForm').is(':visible')) {
            $('#submitDataContent .submitIndicatorsForm h3').html(i18n.review);
            $('#submitDataContent .submitIndicatorsForm h4').filter(':first').html(i18n.about_to_submit_indicator_ratings + ' <mark>' + lowestDD + '</mark>');
            $('.submitIndicatorsForm h3, .submitIndicatorsForm h4').fadeIn(300);
            $('#submitDataFooter .reviewSubmissionButton, .submitIndicatorsForm .indicatorLabels div').fadeOut(300);
            $('#submitDataFooter .submitButton').removeClass('disabled');
            $('#submitDataFilters').animate({
                'background-color': '#f7941d'
            }, 500);
            $('#submitDataFilters h3').hide(300);
            $('#submissionToggle').fadeOut(200);
            setTimeout(function() {
                $('#submitDataFooter .submitButton').fadeIn(300);
            }, 300);
        }
}

// Submit Vulnerability Indicators via UI
function submitSubmitData() {
    var formData = new FormData();
    $('.submitIndicatorsForm input:radio:checked').each(function(index) {
        formData.append(index + 1, $(this).attr('value'));
    });
    formData.append('location', $('#l3_datas').val());
    //formData.append('action', 'vulnerability');
    // Tell S3Import this is an AJAX upload
    formData.append('approach', 'ajax');
    $.ajax({
        url: S3.Ap.concat('/vulnerability/import_vul_ui'),
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    }).done(function(data) {
        $('.indicatorsStart').fadeOut(300);
        displaySubmitDataIndicators();
    }).fail(function() {
        // @ToDo: Something meaningful
        alert('error');
    });
    if ($('#submitDataContent .submitIndicatorsForm').is(':visible')) {
        $('#submitDataContent .submitIndicatorsForm').fadeOut(300);
        $('#indicatorsSubmissionViews .thankyou').fadeIn(300);
        $('#submitDataFooter div, #submitDataFooter mark').fadeOut(300);
        setTimeout(function() {
            $('#submitDataFooter .submitMoreButton').fadeIn(300);
            $('#submitDataFooter .reviewSubmissionButton').addClass('disabled');
            $('.submitIndicatorsForm h3, .submitIndicatorsForm h4').hide();
            $('.submitIndicatorsForm .indicatorLabels div').show();
        }, 300);
    } else if ($('#submitDataContent .dataUploadContainer').is(':visible')) {
        $('#submitDataContent .dataUploadContainer').fadeOut(300);
        $('#dataAndReportsSubmissionViews .thankyou').fadeIn(300);
        $('#submitDataFooter div, #submitDataFooter mark').fadeOut(300);
        setTimeout(function() {
            $('#submitDataFooter .submitMoreButton').fadeIn(300);
        }, 300);
    }
}

function resizeSubmitData() {
    var submitDataHeight = $(window).innerHeight() - 186;
    if (submitDataHeight < 432) {
        submitDataHeight = 432;
    }
    $('#submitDataContent').css('height', submitDataHeight + 'px');
    $('#submitDataFilters').css('height', submitDataHeight + 75 + 'px');
    $('#submitDataSection').css('height', submitDataHeight + 136 + 'px');
}

function showSubmitData(toggle) {
    $('#submitDataContent .dataUploadContainer h3, .delete, .reviewTitling, #submitDataContent .thankyou, .loadingErrorView').hide();
    $('#submitDataFooter div, #submitDataFooter mark').hide();
    $('#submitDataFilters #submissionToggle, #submitDataFilters h3').show();
    $('#dataAndReportsSubmissionViews .dataUploadContainer').show();
    $('.fileType, .labelFile, .remove, .imgDesc, .labelHangRight, .checkHangRight').show();
    $('#submitIndicators, #submitReports').removeClass('active');
    $('#submitDataFilters').css('background-color', '#c6c6c6');
    $('#dataSubmissionRegion').removeClass('mapSubmission imageSubmission otherSubmission demographicsSubmission vcaSubmission loaded').removeAttr('style');
    $('#dataSubmissionRegion input').prop('checked', false);
    $('.dataSubmissionRegion input:radio').each(function() {
        var that = $(this);
        that.parent().removeAttr('style');
        that.prop('disabled', false);
    });
    $('#newSubmissionRegions, #dataSubmissionRegion .submissionContent').empty();
    $('#dataUploadTitle h4').html(i18n.select_data_type);
    switch(toggle) {
        case 'indicators':
            $('.loadingErrorView').fadeOut(300);
            $('#submitDataUpload').html($('#submitDataUpload').html());
            $('#submitIndicators').addClass('active');
            $('#indicatorsSubmissionViews').show();
            $('#dataAndReportsSubmissionViews').hide();
            $('#indicatorsSubmissionViews').children('div').hide();
            $('#submitDataFooter, #submitDataFooter mark').removeAttr('style');
            $('#submitDataFooter .reviewSubmissionButton').removeClass('disabled');
            $('#submitDataContent .indicatorsStart').show();
            break;
        case 'reports':
            $('#submitReports').addClass('active');
            $('#dataAndReportsSubmissionViews').show();
            $('#indicatorsSubmissionViews').hide();
            $('#demoContent').hide();
            $('#uploadDemographicsForm').hide();
            $('.reviewDemographicsView').hide();
            $('#uploadReportsForm').hide();
            $('.uploadReportsForm').hide();
            $('.dataSubmissionRegion').height(46);
            break;
    }
    $('#submitDataFooter').show();
    indicatorsCheckCommune();
    $('#lightbox, #submitDataSection').fadeIn(300);
}

function disableOptionSubmitDataPanel(currentRegionSelector) {
    $(currentRegionSelector + ' input:radio').prop('disabled', true);
    $(currentRegionSelector + ' .mapOption, ' + currentRegionSelector + ' .imageOption, ' + currentRegionSelector + ' .otherOption, ' + currentRegionSelector + ' .demoOption, ' + currentRegionSelector + ' .VCAOption').css('color', '#999');
}

function enableOptionSubmitDataPanel(currentRegionSelector) {
    $(currentRegionSelector + ' input:radio').prop('disabled', false);
    $(currentRegionSelector + ' input:radio').prop('checked', false);
    $(currentRegionSelector + ' .mapOption, ' + currentRegionSelector + ' .imageOption, ' + currentRegionSelector + ' .otherOption, ' + currentRegionSelector + ' .demoOption, ' + currentRegionSelector + ' .VCAOption').css('color', '#000');
}

function selectOptionSubmitData() {
    var currentRegionSelector = '#' + $(this).parent().parent().attr('id');
    var inputValue = $(this).val();
    disableOptionSubmitDataPanel(currentRegionSelector);
    $('#demoContent').hide();
    $('#uploadDemographicsForm').hide();
    $('.reviewDemographicsView').hide();
    $('#uploadReportsForm').hide();
    switch(inputValue){
        case 'map':
        case 'image':
            $('#uploadReportsForm').show();
            $(currentRegionSelector).height(116);
            $('#descFordataSubmissionRegion').keyup(function() {
                if ($('#descFordataSubmissionRegion').val() !== '' && $('#submitDataReportsUpload').val() !== '') {
                    $('#submitDataFooter .submitButton').removeClass('disabled');
                } else {
                    $('#submitDataFooter .submitButton').addClass('disabled');
                }
            });
            $('#submitDataReportsUpload').change(function() {
                if ($('#descFordataSubmissionRegion').val() !== '' && $('#submitDataReportsUpload').val() !== '') {
                    $('#submitDataFooter .submitButton').removeClass('disabled');
                } else {
                    $('#submitDataFooter .submitButton').addClass('disabled');
                }
            });
            $('#submitDataFooter .submitButton').addClass('disabled');
            $('#submitDataFooter .submitButton, #submitDataFooter .cancelButton, #submitDataFooter mark').fadeIn(300);
            break;
        case 'other':
        case 'vca':
            $('#uploadReportsForm').show();
            $(currentRegionSelector).height(86);
            $('#descFordataSubmissionRegion').hide();
            $('#fakeFordataSubmissionRegion').hide();
            $('#submitDataReportsUpload').change(function() {
                    if ($('#submitDataReportsUpload').val() !== '') {
                        $('#submitDataFooter .submitButton').removeClass('disabled');
                    }
                });
            $('#submitDataFooter .submitButton').addClass('disabled');
            $('#submitDataFooter .submitButton, #submitDataFooter .cancelButton').fadeIn(300);
            break;
        case 'demographics':
            var d=new Date();
            yr=d.getFullYear();
            for (var x = 0; x <= 6; x++) {
                $('#reportDate'+x).datepicker({
                    dateFormat: 'yy-mm-dd',
                    defaultDate: yr+'-01-01',
                    changeYear: true,
                    changeMonth: true,
                    maxDate: '+0d',
                    minDate: '-20y'
                 });
            }
            $('#demoContent').show();
            $('#uploadDemographicsForm').hide();
            $('.reviewDemographicsView').hide();
            $(currentRegionSelector).height(330);
            $('#submitDataFooter .submitButton').addClass('disabled');
            $('#submitDataFooter .submitButton, #submitDataFooter .cancelButton').fadeIn(300);
            $('.sourceLabel').children('mark').hide();
            $('#demoContent input').each(function() {
                $(this).val('')
                       .change(onChangeData);
            });
            break;
    }
    if ($(currentRegionSelector + ' .submissionContent').is(':visible')) {
        $(currentRegionSelector + ' .submissionContent').fadeOut(300);
    }
}

function demographicsUploadDisplay(id){
    $('#demoContent').hide();
    $('.reviewDemographicsView').hide();
    $('#uploadDemographicsForm').show();
    // Current Region
    $('#' + $(this).parent().parent().attr('id')).height(120);
    $('#submitDataFooter .submitButton').fadeOut(300);
}

// Import Demographic Data via CSV
function demographicsLoader(id) {
    // $('#uploadDemographicsButton') has been clicked
    // Hide any error message
    $('.loadingErrorView').fadeIn(300);
    var formData = new FormData($('#uploadDemographicsForm')[0]);
    //formData.append('action', 'demographics_part1');
    // Tell S3Import this is an AJAX upload
    formData.append('approach', 'ajax');
    $.ajax({
        url: S3.Ap.concat('/vulnerability/import_demo_csv_part1/import.aadata'),
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    }).done(function(data) {
        if (data['Error']) {
            /* Display the error */
            $('#errormsg').html(data['Error']);
            $('.loadingErrorView').fadeIn(300);
        } else {
            submitDataJobID = data['upload_id'];
            submitDataItemIDs = data['items'];
            submitNextAction = 'demographics_part2';
            submittedData = data['data'];
            submittedDataPage = 0;
            $('.indicatorsStart').fadeOut(300);
            displayDemoData();
        }
    }).fail(function() {
        // @ToDo: Something meaningful
        alert('error');
    });
}

function displayDemoData() {
    if (submittedData) {
        total_pages = submittedData.length;
        page_data = submittedData[submittedDataPage];
        page = submittedDataPage + 1;
    }
    // Clear the file input field
    disableOptionSubmitDataPanel('#dataSubmissionRegion');
    $('#submitDemoUpload').html($('#submitDemoUpload').html());
    $('.reviewDemographicsView h3').html(i18n.review + " <span class='currentPage'>" + page + '</span> ' + i18n.of + " <span class='totalPages'>" + total_pages + '<span>');
    $('.reviewDemographicsView h4 mark').html(page_data['location']);
    $('#reportViewDate').html(page_data['date']);
    $('#demoViewField0').html(page_data['data']['Population']);
    $('#sourceViewField0').html(page_data['source']);
    $('#demoViewField1').html(page_data['data']['Male']);
    $('#sourceViewField1').html(page_data['source']);
    $('#demoViewField2').html(page_data['data']['Female']);
    $('#sourceViewField2').html(page_data['source']);
    $('#demoViewField3').html(page_data['data']['Over 60']);
    $('#sourceViewField3').html(page_data['source']);
    $('#demoViewField4').html(page_data['data']['Under 5']);
    $('#sourceViewField4').html(page_data['source']);
    $('#demoViewField5').html(page_data['data']['Households']);
    $('#sourceViewField5').html(page_data['source']);
    $('#demoViewField6').html(page_data['data']['Households below poverty line']);
    $('#sourceViewField6').html(page_data['source']);

    $('#uploadDemographicsForm').hide();
    $('.reviewDemographicsView.firstPage').show();
    $('.reviewDemographicsView h3').show();
    $('#submissionToggle').hide(300);
    if (page == 1) {
        $('#submitDataFooter mark, #submitDataFooter .reviewNextButton').fadeIn(300);
        $('.backButton').hide();
    }
    if (page > 1 && !$('.backButton').is(':visible')) {
        $('.backButton').fadeIn(300);
    }
    if (page == total_pages) {
        $('.reviewNextButton').hide();
        $('.submitAllButton').show();
    } else {
        $('.reviewNextButton').show();
        $('.submitAllButton').hide();
    }
}
function onChangeData() {
    var that = $(this);
    if (that.hasClass('demoField')) {
        /* Demographic data: If a value is entered then the source becomes a requirement */
        if (that.val() === '') {
            that.siblings('.sourceLabel').children('mark').hide();
            that.siblings('.dateLabel').children('mark').hide();
        } else {
            that.siblings('.sourceLabel').children('mark').show();
            that.siblings('.dateLabel').children('mark').show();
        }
    }
    /* Demographic data: To enable the submit button at least one value needs to be entered
                         and all source & date fields linked with a value need to be provided */
    var canShowSubmit = false;
    $('#demoContent .demoField').each(function() {
         if ($(this).val() !== '') {
            canShowSubmit = true;
         }
    });
    $('#demoContent .sourceLabel mark').each(function() {
        if ($(this).is(':visible') && $(this).parent().siblings('.sourceField').val() === '') {
            canShowSubmit = false;
            $('#submitDataFooter .submitButton').addClass('disabled');
            return;
        }
    });
    $('#demoContent .dateLabel mark').each(function() {
        if ($(this).is(':visible') && $(this).parent().siblings('.dateField').val() === '') {
            canShowSubmit = false;
            $('#submitDataFooter .submitButton').addClass('disabled');
            return;
        }
    });
    if (canShowSubmit) {
        $('#submitDataFooter .submitButton').removeClass('disabled');
    } else {
        $('#submitDataFooter .submitButton').addClass('disabled');
    }
}

function cancelSubmitDataTypeSelection() {
    var uploadReportsForm = $('#uploadReportsForm');
    uploadReportsForm.html(uploadReportsForm.html()); // ?
    indicatorsCheckCommune();
    $('#demoContent').hide();
    $('#uploadDemographicsForm').hide();
    $('.reviewDemographicsView').hide();
    uploadReportsForm.hide();
    $('#dataSubmissionRegion').height(46);
    $('#submitDataFooter div, #submitDataFooter mark').fadeOut(300);
}

function uploadSubmitDataReport(button) {
    var currentRegionSelector = '#dataSubmissionRegion';
    var inputValue = $(currentRegionSelector + ' input[type=radio]:checked').val();
    var formData;
    if (inputValue == 'demographics') {
        formData = new FormData();
        jQuery.each($(currentRegionSelector + ' .demographicsForm input'), function(i, input) {
            formData.append(input.id, input.value);
        });
    } else {
        formData = new FormData($(currentRegionSelector + ' .uploadReportsForm')[0]);
    }
    $('.dataUploadContainer').fadeOut(300);
    formData.append('action', inputValue);
    var level = selectedLevel();
    var location = $('#' + level + '_datas').val();
    formData.append('location', location);
    //formData.append('desc', $('#descFordataSubmissionRegion').val());
    displayThanks('#dataAndReportsSubmissionViews', i18n.uploading_report_details, null);
    $.ajax({
        url: S3.Ap.concat('/vulnerability/submitData'),
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    }).done(function(data) {
        // Redisplay the screen for any more data entry
        cancelSubmitDataTypeSelection();
        displayThanks('#dataAndReportsSubmissionViews', i18n.upload_successful, 5000);
        $('.dataUploadContainer').fadeIn(300);
    }).fail(function() {
        // @ToDo: Something meaningful
        alert('error');
    });
}

// End
